﻿using System;
using System.Threading;
using System.Windows.Input;
using Hopscotch.Presentation.Common;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;

namespace Hopscotch.Application.Shell.Commands
{
    public class CreateShellCommand : ICommand
    {
        private readonly IUnityContainer container;
        private readonly IRegionManager regionManager;
        private readonly IAppController appController;
        private bool shellInOwnThread = true;

        public CreateShellCommand(IUnityContainer container, IRegionManager regionManager, IAppController appController)
        {
            this.container = container;
            this.regionManager = regionManager;
            this.appController = appController;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged
        {
            add { }
            remove { }
        }

        public void Execute(object parameter)
        {
            if (shellInOwnThread)
            {
                Thread thread = new Thread(() =>
                {
                    var sw = CreateShell();

                    sw.Show();
                    sw.Closed += (sender2, e2) =>
                        sw.Dispatcher.InvokeShutdown();

                    System.Windows.Threading.Dispatcher.Run();
                });

                thread.Name = "Shell";
                thread.IsBackground = true;
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
            }
            else
            {
                var sw = CreateShell();
                sw.Show();
            }
        }

        private ShellWindow CreateShell()
        {
            var scopedRegionManager = regionManager.CreateRegionManager();

            ShellViewModel shellVM = new ShellViewModel(container, scopedRegionManager, appController);
            ShellWindow sw = new ShellWindow(shellVM);

            return sw;
        }
    }
}
